import axios from 'axios'
import config  from './config';
import { ElMessage } from 'element-plus';
import { useLoading} from 'store/loading.js'
import router from '@/router'
const token = useToken()

const {add , reduce} = useLoading()
const instance  = axios.create(config)
instance.interceptors.request.use(
    config => {
    config.headers['Authorization'] =  token.getToken
        add()
        return config
    },
    ()=>{
        reduce()
        ElMessage({
            message:'请求格式错误',
            grouping:true,
            type:'error'
        })
    }
)

instance.interceptors.response.use(
    res => {
        reduce()
        if(res.status != 200){
            return [ res.data]
        }
        if(res.status == 302){
          
            ElMessage({
                message:'登录已过期，请重新登录',
                grouping:true,
                type:'error'
            })   
            router.replace('/')
            return
        }
        const code = res.data.code | res.data.status
        if(![0,200].includes(code)){
            ElMessage({
                message: res.data.msg || '请求失败',
                grouping:true,
                type:'error'
            })
            return [res.data]
        }
        return [ , res.data]
    },
    err => {
        reduce()
        return [err]
    }
)

export const GET =(url,data) =>{
    if (data) {
        return instance.get(url, { params: data })
    }
    return instance.get(url)
}
export const POST = (url,data) =>{
    return instance.post(url,data)
}
export const PUT = (url,data) =>{
    return instance.put(url,data)
}

export const DEL = (url) =>{
    return instance.delete(url)
}
export const POST_FORM = (url,data) =>{
    return instance.post(url,data,{
        headers:{
            'Content-Type':'multipart/form-data'
        }
    })
}

